﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Lizk.DShowPlayer;
using System.IO;
using Lizk.SimpleHUD;
using SharpMedia.Pages;
using System.Diagnostics;
using System.Reflection;
using System.Linq;
using System.Threading;
using MediaData;

namespace SharpMedia
{
    public static partial class Util
    {
        public static int CountDigits(int i)
        {
            int ret = 0;
            while (i > 0)
            {
                i /= 10;
                ret++;
            }
            if (ret == 0)
                ret = 1;
            return ret;
        }


        public static MediaDataSet.EpisodesRow SelectEarliestUnwatchedEpisode(MediaDataSet.TitlesRow title)
        {
            return (from e in title.GetEpisodesRows()
                    where e.Watched == 0
                    orderby e.Season, e.Episode
                    select e).FirstOrDefault();
        }

        public static bool IsTitleOffline(MediaDataSet.TitlesRow title)
        {
            var volumes = (from file in title.GetFilesRows()
                           select file.Volume).Distinct();

            foreach (string volume in volumes)
            {
                if (SharpMedia.RootManager.IsOnline(volume))
                    return false;
            }
            return true;
        }
        public static string PrintVolumeInfo(MediaDataSet.TitlesRow title)
        {
            var volumes = (from file in title.GetFilesRows()
                           where !SharpMedia.RootManager.IsOnline(file.Volume)
                           select file.Volume).Distinct();

            string s = "";
            foreach (string volume in volumes)
            {
                if (s == "")
                    s = string.Format("{0}", volume);
                else
                    s += "\n" + string.Format("{0}", volume);
            }
            return s;
        }

        public static MediaDataSet.FilesRow GetDBFileFromPath(string fullPath)
        {
            string volume = new DriveInfo(fullPath).VolumeLabel;

            string path = fullPath.Replace(SharpMedia.RootManager.GetRoot(volume) + Path.DirectorySeparatorChar, "");
            MediaDataSet.FilesRow file = (MediaDataSet.FilesRow)SharpMedia.Database.Data.Files.Rows.Find(new object[] { volume, path });
            return file;
        }

        public static IEnumerable<MediaDataSet.EpisodesRow> GetEpisodeFromPath(string fullPath)
        {
            MediaDataSet.FilesRow file = GetDBFileFromPath(fullPath);
            if (file != null)
            {
                var episodes = from e in file.GetEpisodeFilesRows()
                               select e.EpisodesRow;

                return episodes;
            }
            return null;
        }

        public static string GetDBFilePath(MediaDataSet.FilesRow file)
        {
            return Path.Combine(SharpMedia.RootManager.GetRoot(file.Volume), file.Path);
        }


        public static void TryScrape(HUDPage parent, MediaDataSet.TitlesRow title)
        {
            ScraperHandler.ScraperState state = SharpMedia.ScraperHandler.Get(title);

            switch (state == null ? ScraperHandler.ScraperStatus.None : state.Status)
            {
                case ScraperHandler.ScraperStatus.None:
                case ScraperHandler.ScraperStatus.Done:
                    SharpMedia.ScraperHandler.Scrape(title);
                    break;
                case ScraperHandler.ScraperStatus.MultipleResults:
                    SharpMedia.Navigate(new ScraperResultPage(parent, title));
                    break;
                case ScraperHandler.ScraperStatus.Error:
                    SharpMedia.Navigate(new ScraperSearchPage(parent, title));
                    break;
            }
        }

        public static string[] AvailableDVDs()
        {
            List<string> drives = new List<string>();
            foreach (DriveInfo di in DriveInfo.GetDrives())
            {
                if (di.DriveType == DriveType.Network)
                    continue;

                if (!di.IsReady)
                    continue;

                string path = Path.Combine(di.RootDirectory.FullName, @"video_ts\video_ts.ifo");

                if (File.Exists(path))
                {
                    drives.Add(path);
                }
            }
            return drives.ToArray();
        }

        public static void MountImage(string path) { Process.Start(SharpMedia.Settings.MountProgramPath, string.Format(SharpMedia.Settings.MountProgramArguments, path)).WaitForExit(); }


        public static bool IsEpisodeOffline(MediaDataSet.EpisodesRow episode)
        {
            var files = from f in episode.GetEpisodeFilesRows()
                        where SharpMedia.RootManager.IsOnline(f.FilesRowParent.Volume)
                        select f.FilesRowParent;

            return files.Count() == 0;
        }

        public static string[] GetEpisodeVolumes(MediaDataSet.EpisodesRow episode)
        {
            var volumes = from f in episode.GetEpisodeFilesRows()
                          select f.FilesRowParent.Volume;
            return volumes.ToArray();
        }

    }

}
